package com.wms.handler;

import com.basis.utils.CodeGenerateRuleUtil;
import com.eam.data.WmsDeliveryResultValue;
import com.mes.data.EmesColor;
import com.mes.data.EmesSize;
import com.mes.data.EmesVendor;
import com.mes.quality.data.EmesqInspectionItem;
import com.wms.entity.WmsDeliveryDetail;
import com.wms.entity.WmsStorageBatch;
import com.wms.entity.WmsStorageBatchItem;
import com.wms.entity.WmsStorageInOut;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.model.common.enterprise.Locator;
import org.openbravo.model.common.enterprise.Warehouse;
import org.openbravo.model.common.plm.Product;
import org.openbravo.model.common.uom.UOM;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;



/**
 * 录入检验结果
 */
public class QualityQueryResultHandler extends BaseActionHandler {
	private Logger logger = Logger.getLogger(this.getClass());

	@Override
	protected JSONObject execute(Map<String, Object> parameters, String data) {
		JSONObject jsonRep = new JSONObject();
		try {
			OBContext.setAdminMode();
			JSONObject reqData = new JSONObject(data);
			JSONArray jsonIds = reqData.getJSONArray("result");
			JSONObject temp = null;

			boolean flag = true;
			String failMsg = "";
			if (jsonIds != null && jsonIds.length() > 0) {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

				Date time  =sdf.parse(sdf.format(new Date()));  //获取当前系统时间

				for (int i = 0; i < jsonIds.length(); i++) {
					temp = jsonIds.getJSONObject(i);

					long QtyError = temp.isNull("QTY_ERROR") ? 0 : temp.getInt("QTY_ERROR");//不合格数量
					long QTYTEST = temp.isNull("QTY_TEST") ? 0 : temp.getInt("QTY_TEST");//总采购数量
					long QTYIN = temp.isNull("QTYIN") ? 0 : temp.getInt("QTYIN");//入库数量
					long QTY_back = temp.isNull("QTY_BACK") ? 0 : temp.getInt("QTY_BACK");//退货数量
					long qty = temp.isNull("QTY") ? 0 : temp.getInt("QTY"); //检验数量
					long KCQRY = temp.isNull("KCQRY") ? 0 : temp.getInt("KCQRY"); //已入库数量

					long sumqty = 	QTYIN +KCQRY;
					if(QTYTEST < QTYIN+QTY_back+KCQRY){
						jsonRep.put("msg", "入库数量超过库存数量！");
						return jsonRep;
					}


					String valuestatus ="";
					String XMID = "";
					String WLID = "";
					String DETAILID = "";
					String CKID = "";
					String KWID = "";
					String DWID = "";
					String YSID = "";
					String CMID = "";
					String CGCODE = "";
					String CGID = "";
					String GYSID = "";
					String result = "";
					String DDCODE = "";


					if(temp.has("XMID")){
						XMID = temp.getString("XMID");
					}
					if(temp.has("WLID")){
						WLID = temp.getString("WLID");
					}
					if(temp.has("DETAILID")){
						DETAILID = temp.getString("DETAILID");
					}
					if(temp.has("CKID")){
						CKID = temp.getString("CKID");
					}
					if(temp.has("KWID")){
						KWID = temp.getString("KWID");
					}
					if(temp.has("DWID")){
						DWID = temp.getString("DWID");
					}
					if(temp.has("YSID")){
						YSID = temp.getString("YSID");
					}
					if(temp.has("CMID")){
						CMID = temp.getString("CMID");
					}
					if(temp.has("CGCODE")){
						CGCODE = temp.getString("CGCODE");
					}
					if(temp.has("CGID")){
						CGID = temp.getString("CGID");
					}
					if(temp.has("GYSID")){
						GYSID = temp.getString("GYSID");
					}
					if(temp.has("RESULT")){
						result = temp.getString("RESULT");
					}

					WmsDeliveryDetail Detail = OBDal.getInstance().get(WmsDeliveryDetail.class, DETAILID);
					if("1".equals(result)){
						result = "合格";
						if(i == 0){

							String sql = "select u.wms_storage_batch_id as BATCHID from wms_storage_batch u where u.emes_color_id = '"+YSID+"' and u.emes_size_id = '"+CMID+"' and u.m_product_id =  '"+WLID+"' ";

							String BATCHID = (String) OBDal.getInstance().getSession().createSQLQuery(sql).uniqueResult();


							String aql = " SELECT   " +
									"   fl.value   " +
									"FROM   " +
									"   m_product wl,   " +
									"   m_product_category fl    " +
									"WHERE   " +
									"   wl.m_product_category_id = fl.m_product_category_id   " +
									"and wl.m_product_id = '"+WLID+"'    ";

							String productType = (String) OBDal.getInstance().getSession().createSQLQuery(aql).uniqueResult();



							WmsStorageBatch batch = null;

							String status = "normal";
							Product WL = OBDal.getInstance().get(Product.class, WLID);
							EmesVendor gys = OBDal.getInstance().get(EmesVendor.class, GYSID);
							UOM uom = OBDal.getInstance().get(UOM.class, DWID);
							EmesColor color = OBDal.getInstance().get(EmesColor.class, YSID);
							EmesSize size = OBDal.getInstance().get(EmesSize.class, CMID);
							Warehouse ck =OBDal.getInstance().get(Warehouse.class, CKID);
							Locator kw =OBDal.getInstance().get(Locator.class, KWID);
						//	WmsDelivery cg = OBDal.getInstance().get(WmsDelivery.class, CGID);
							//注释前
							if(productType.equals("SC-XT") || productType.equals("SC_DD")){

								String RfidCode = null;
								if(productType.equals("SC-XT")){
									RfidCode = CodeGenerateRuleUtil.getCode("Wms_Storage_Batch", "Batch_No");  //明细RFID批次
								}else if(productType.equals("SC_DD")){
									RfidCode = CodeGenerateRuleUtil.getCode("Wms_Storage_Batch", "Is_Self");  //明细RFID批次
								}


								//存入大底的批次记录(storage_batch)
								if(BATCHID != null){
									batch = OBDal.getInstance().get(WmsStorageBatch.class, BATCHID);
								}else{
									batch = new WmsStorageBatch();
								}


								batch.setBatchNo(RfidCode);
								batch.setProduct(WL);
								batch.setEmesVendor(gys);
								batch.setUom(uom);
								batch.setStatus(status);
								batch.setEmesColor(color);
								batch.setEmesSize(size);
								batch.setTime(time);

								OBDal.getInstance().save(batch);
								OBDal.getInstance().flush();


								//存入大底的批次明细记录（storage_in_out）
								BigDecimal numbers = new BigDecimal(QTYTEST);
								BigDecimal numbersIn = new BigDecimal(QTYIN);

								WmsStorageInOut Storage = new WmsStorageInOut();
								Storage.setWmsStorageBatch(batch);
								Storage.setWarehouse(ck);
								Storage.setLocator(kw);
								Storage.setQty(numbersIn);
								Storage.setOptMode("采购入库");
								Storage.setUom(uom);
								Storage.setOptCode(CGCODE);
								Storage.setData(CGID);
								Storage.setStatus("OK");
								OBDal.getInstance().save(Storage);

								for(long t = 0 ; t< QTYIN ; t++){

									String Batch_No =CodeGenerateRuleUtil.getCode("Wms_Storage_Batch_Item", "Description");  //大底生成对应批次

									String kuanshi =  WL.getSearchKey().toString().substring(4,6);
									String sizeCode =  size.getCode().toString();
									DDCODE = "S"+kuanshi+"-"+sizeCode+"-"+Batch_No;
									for(int a = 0; a< 2; a++){

										WmsStorageBatchItem item = new WmsStorageBatchItem();

										item.setType("大底");
										if(a == 0){
											item.setCode(DDCODE+"-L");
											item.setFootType("left");
										}else{
											item.setCode(DDCODE+"-R");
											item.setFootType("right");
										}

										item.setWmsStorageBatch(batch);
										item.setStatus("CREATE");
										OBDal.getInstance().save(item);

								}

								}
							}else{

								if(BATCHID != null){
									batch = OBDal.getInstance().get(WmsStorageBatch.class, BATCHID);
								}else{

									batch = new WmsStorageBatch();

									batch.setProduct(WL);
									batch.setEmesVendor(gys);
									batch.setUom(uom);
									batch.setStatus(status);
									batch.setEmesColor(color);
									batch.setEmesSize(size);
									batch.setTime(time);

									OBDal.getInstance().save(batch);
									OBDal.getInstance().flush();
								}
								//存入大底的批次明细记录（storage_in_out）
								BigDecimal numbers = new BigDecimal(QTYTEST);
								BigDecimal numbersIn = new BigDecimal(QTYIN);

								WmsStorageInOut Storage = new WmsStorageInOut();
								Storage.setWmsStorageBatch(batch);
								Storage.setWarehouse(ck);
								Storage.setLocator(kw);
								Storage.setQty(numbersIn);
								Storage.setUom(uom);
								Storage.setOptCode(CGCODE);
								Storage.setData(CGID);
								Storage.setStatus("OK");
								OBDal.getInstance().save(Storage);

							}

						}
					} else {
						result = "不合格";
						BigDecimal numbersIn = new BigDecimal(QTYIN);
						Detail.setQtyBack(numbersIn);
					}

					WmsDeliveryResultValue resultValue = new WmsDeliveryResultValue();

					EmesqInspectionItem resultValues = OBDal.getInstance().get(EmesqInspectionItem.class, XMID);


					BigDecimal sumNums = new BigDecimal(sumqty);

					//resultValue = OBDal.getInstance().get(WmsDeliveryResultValue.class, result_Value_Id);

					//修改 原始采购订单相关物料出库数量
					resultValue.setQty(qty);
					resultValue.setEmesqInspectionItem(resultValues);
					resultValue.setWmsDeliveryDetail(Detail);
					resultValue.setQtyError(QtyError);
					resultValue.setResult(result);
					OBDal.getInstance().save(resultValue);

					if(QTYTEST == QTYIN+QTY_back+KCQRY){
						valuestatus = "OK";
					}else{
						valuestatus = "PART";
					}
					Detail.setStatus(valuestatus);
					if(result != "不合格"){
						Detail.setQtyIn(sumNums);
					}
					OBDal.getInstance().save(Detail);

				}
			} else {
				flag = false;
				failMsg = "";
			}
			if (flag) {
				OBDal.getInstance().commitAndClose();
				jsonRep.put("result", true);
				jsonRep.put("msg", "录入成功");
			} else {
				OBDal.getInstance().rollbackAndClose();
				jsonRep.put("result", false);
				jsonRep.put("msg", failMsg);
			}
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			e.printStackTrace();
			logger.error("录入失败：", e);
			try {
				jsonRep.put("result", false);
				jsonRep.put("msg", "录入失败，"+e.getMessage());
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
		} finally {
			OBContext.restorePreviousMode();
		}
		return jsonRep;
	}
}